package com.apps.compress;

import com.apps.sexctption.NullException;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 把文件压缩成zip
 */
public class ZipComPressHelper
{
    /**
     * 压缩成zip,输出到文件所在目录
     * @param path
     * @throws IOException
     */
    public static String writeZip(String path) throws IOException
    {
        byte[] buf = new byte[8192];
        int len;
        File file = new File(path);
        if (!file.isFile())
                throw new NullPointerException("文件"+path+"不存在");
        String zipSavePath=file.getAbsolutePath().split("\\.")[0]+".zip";
        //校验压缩包是否已经存在
        File zip=new File(file.getAbsolutePath().split("\\.")[0]+".zip");
        if(zip.isFile()) {
            throw new NullException(zip.getAbsolutePath()+"---已经存在");
        }
        OutputStream os = new BufferedOutputStream(new FileOutputStream(zipSavePath));
        ZipOutputStream zos = new ZipOutputStream(os);
        ZipEntry ze = new ZipEntry(file.getName());
        zos.putNextEntry(ze);
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        while ((len = bis.read( buf ) ) > 0 ) {
                zos.write( buf, 0, len );
        }
        zos.closeEntry();
        zos.closeEntry();
        zos.close();
        bis=null;
        file = null;
        return zipSavePath;
    }

    public static void main(String... args) throws Exception
    {
//        File file = new File("I:\\素材\\PPT素材\\毕业答辩\\毕业答辨(1).pptx");
//        System.out.println(file.getPath().split("\\.")[0]);
        try
        {
            writeZip("I:\\素材\\PPT素材\\毕业答辩\\毕业答辨(1).pptx");
        }catch (Exception e)
        {
            e.printStackTrace();
        }

    }
}
